package com.itcast.demo.algorithm;


import java.util.HashMap;
import java.util.Map;

public class WeightRoundRobin {
    private static final Map<String, Weight> weightMap = new HashMap<>();
    private static final int totalWeight;
    static{
        ServerIps.WEIGHT_LIST.forEach((key, value) ->{
            weightMap.put(key, new Weight(key, value, 0));
        });
        totalWeight = ServerIps.WEIGHT_LIST.values().stream().reduce(0, Integer::sum);
    }
    public static void main(String [] args){
        for (int i = 0; i < 10; i++) {
            System.out.println("getServer() = " + getServer());
            
        }
        
    }

    public static String getServer() {
        // 所有ip的CurrentWeight统一加上原始权重 0+5
        for (Weight weight : weightMap.values()) {
            weight.setCurrentWeight(weight.getCurrentWeight()+weight.getWeight());

        }
        // 找到CurrentWeight 最大值 maxCurrentWeight：5
        Weight maxCurrentWeight = null;
        for (Weight weight : weightMap.values()) {
            if (maxCurrentWeight == null|| weight.getCurrentWeight()>maxCurrentWeight.getCurrentWeight()) {
                maxCurrentWeight = weight;

            }
        }
        // 将maxCurrentWeight 减去总权重和 5-7
        maxCurrentWeight.setCurrentWeight(maxCurrentWeight.getCurrentWeight() - totalWeight);
        // 返回maxCurrentWeight 所对应的ip  5对应ip：A
        return maxCurrentWeight.getIp();
    }
}
